package de.koller.singularity.engine.tile;

import de.koller.singularity.SNode;
import java.util.HashSet;
import java.util.Set;

public class STileMap extends SNode {
	public static final int	MAX_LOADED_MAPS = 5;
	
	public final TileCreator tileCreator = new TileCreator();
	private final Set<TileMapSave> saves = new HashSet<>(); 
	
	public STile[] getTileAt( String system, long x, long y ) {
		TileMapSave mapSave = getMapSave( system, x, y );
		mapSave.setLastTimeUsed( sroot.getGameTime() );
		return mapSave.getTile( system, x, y );
	}
	
	public void setTileAt( String system, long x, long y, STile... tiles ) {
		TileMapSave mapSave = getMapSave( system, x, y );
		mapSave.setLastTimeUsed( sroot.getGameTime() );
		mapSave.setTile( system, x, y, tiles );
	}

	private TileMapSave getMapSave( String system, long x, long y ) {
		for( TileMapSave s : saves )
			if( s.isInBounds( system, x, y ) )
				return s;
		
		long vx = (long)Math.floor( x / (double)TileMapSave.CHUNK_SIZE ) * TileMapSave.CHUNK_SIZE;
		long vy = (long)Math.floor( y / (double)TileMapSave.CHUNK_SIZE ) * TileMapSave.CHUNK_SIZE;
		
		TileMapSave s = new TileMapSave( system, vx, vy, tileCreator );
		saves.add( s );
		return s;
	}
	
	public static void main( String[] args ) {
		int c = 5;
		for( int i = -10; i < 10; i++ ) {
			int vi =  (int)Math.floor( i / (double)c ) * c;
			System.out.println( i + " = " + vi );
		}
	}
	
	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
		
		if( saves.size() > MAX_LOADED_MAPS ) {
			TileMapSave oldest = null;
			for( TileMapSave s : saves )
				if( oldest == null )
					oldest = s;
				else
					if( s.getLastTimeUsed() < oldest.getLastTimeUsed() )
						oldest = s;
			saves.remove( oldest );
			oldest.save();
		}
	}
	
	@Override
	protected void release() {
		super.release();
		
		for( TileMapSave s : saves )
			s.save();
	}
	
}
